package com.sunwhite.herostore.service;

import com.sunwhite.herostore.common.MySqlSessionFacoty;
import com.sunwhite.herostore.common.async.AsyncOperation;
import com.sunwhite.herostore.common.async.AsyncOperationProcessor;
import com.sunwhite.herostore.entity.UserEntity;
import com.sunwhite.herostore.mapper.IUserDao;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.function.Function;

public class LoginService {
    /**
     * 日志对象
     */
    private final static Logger log= LoggerFactory.getLogger(LoginService.class);
    /**
     * 单例对象
     */
    private static LoginService loginService =new LoginService();
    /**
     * 私有化类构造器
     */
    private LoginService(){

    }

    /***
     * 获取单例对象
     * @return 单例对象
     */
    public static LoginService getInstance(){
        return loginService;
    }

    /**
     * 用户登录
     * @param userName
     * @param password
     * @return
     */
    public void login(String userName, String password, Function<UserEntity,Void> callback){
        if (userName==null||password==null){
            return ;
        }

        AsyncOperation asyncGetUserByName = new AsyncGetUserByName(userName, password){
            @Override
            public void doFinish() {
                //执行回调函数
                callback.apply(this.getUserEntity());
            }
        };
        AsyncOperationProcessor.getInstance().process(asyncGetUserByName);
    }

    /**
     * 创建异步操作执行器
     */
    private class AsyncGetUserByName implements AsyncOperation {

        /**
         * 用户名称
         */
        private final String userName;

        /**
         * 密码
         */
        private final String password;

        /**
         * 用户实体
         */
        private UserEntity userEntity = null;
        /**
         * 类参数构造器
         *
         * @param userName 用户名称
         * @param password 密码
         * @throws IllegalArgumentException if null == userName || null == password
         */
        AsyncGetUserByName(String userName, String password) {
            if (null == userName ||
                    null == password) {
                throw new IllegalArgumentException();
            }

            this.userName = userName;
            this.password = password;
        }

        @Override
        public int getBingId() {
            return userName.charAt(userName.length()-1);
        }

        /**
         * 需要执行的异步操作
         */
        @Override
        public void doAsync() {
            //使用try with 的写法 自动调用 sqlSession 的 close 方法
            try(SqlSession sqlSession = MySqlSessionFacoty.openSession()){
                //获取dao对象
                IUserDao iUserDao = sqlSession.getMapper(IUserDao.class);

                //查看当前线程的名称
                log.info("当前线程：therdId->{},threadName->{}",Thread.currentThread().getId(),Thread.currentThread().getName());

                UserEntity userEntity = iUserDao.getUserByName(userName);
                if (userEntity==null){
                    userEntity = new UserEntity();
                    userEntity.userName=userName;
                    userEntity.password=password;
                    userEntity.heroAvatar="Hero_Shaman";
                    iUserDao.insertInto(userEntity);
                }else if (!password.equals(userEntity.password)){
                    log.error("用户密码错误，userId={},userName={}",userEntity.userId,userEntity.userName);
                    throw new RuntimeException("用户密码错误!");
                }
                this.userEntity=userEntity;
            } catch (Exception e) {
                log.error(e.getMessage(),e);
            }
        }

        /**
         * 获取用户实体
         * @return
         */
        protected UserEntity getUserEntity() {
            return userEntity;
        }
    }


}
